var param = null;
var rows = null;
var imgInfo = null;
var searchParam = {shop_id:"", userid:"", shop_name:"", goods_name: "", state: ""};
$(function(){
	searchParam.shop_id = $("#key_shop_id").val();
	jQuery("#gridTable1").jqGrid({
		url: basePath + '/server/ajax.do',
		datatype: 'json',
		height: 250,
		autowidth: true,
	   	colNames:['商品名称','所属店铺', '状态', '上架时间', '展示图片'],
	   	colModel:[
	   		{name:'goods_name',index:'s.goods_name', width:200},
	   		{name:'shop_name',index:'t.shop_name', width:80},
	   		{name:'state',index:'s.state', width:60, align:"center", formatter: function(cellvalue, options, rowObject) {
				if(cellvalue == 1){
					return "正常";
				} else if(cellvalue == 2) {
					return "缺货";
				} else {
					return "下架";
				}
			}},
	   		{name:'add_time',index:'s.add_time', width:80, align:"left", formatter: function(cellvalue, options, rowObject) { return cellvalue.substr(0, 16); }},		
	   		{name:'goods_id', width:60, align:"center", sortable:false, formatter: function(cellvalue, options, rowObject) {
				return "<a href='javascript:optImages(\"" + cellvalue + "\", \"" + rowObject.goods_name + "\")' style='color:#F60;'>操作</a>";
			}}
	   	],
	   	beforeRequest:function(){//向服务器端发起请求之前触发此事件但如果datatype是一个function时例外
        	param = $("#gridTable1").jqGrid("setGridParam")[0].p;
        	rows = null;
			$("#gridTable1").jqGrid("setGridParam", { //设置查询参数
				postData:{
					"iFunc": AjaxUtil.command.FUNC_PAGING,
					"strData": $.toJSON({
						sqlID: "sjc_goods_manage_1",
						parameters: {sortname:param.sortname, sortorder:param.sortorder,
							shop_id: searchParam.shop_id,
							goods_name: searchParam.goods_name,
							state: searchParam.state
						},
						offset: (param.page-1)*param.rowNum,
						maxsize: param.rowNum
					})
				}
			});
		},
		jsonReader: {
			root: "query",			// 数据行（默认为：rows）
            page: function (obj) { // 当前页
            		rows = obj.query;
            		return param.page;
            	},
            total: function (obj) { return Math.ceil(obj.total/param.rowNum); },			// 总页数
            records: "total",		// 总记录数
            repeatitems: false,
			id: "goods_id"
		},
	   	multiselect: true,
	   	sortname: 's.add_time',
	    sortorder: "desc",
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: '#gridPager1',
	   	caption: "商品管理"
	});
	jQuery("#gridTable1").jqGrid("navGrid", "#gridPager1", {
		search : false,
        addfunc : openAdd,
        editfunc : openEdit,
        delfunc : openDel,
        alerttext : "请选择需要操作的数据行!"  // 当未选中任何行而点击编辑、删除、查看按钮时，弹出的提示信息  
    }).jqGrid('navButtonAdd',"#gridPager1",{
    	caption : '',
    	title : '查找',
    	position : 'first',
    	buttonicon : 'ui-icon-search',
    	onClickButton : openSearch
    });
    
    var tree_data = AjaxUtil.command.executeQueryTransaction([{sqlID:"sjc_goods_type_2"},{sqlID:"sjc_goods_manage_7"}]);
	if(AjaxUtil.command.isSucceed(tree_data)) {
		zNodes = tree_data.rows[0];
		for(var i=0; i<zNodes.length; i++) {
			for(var j=i+1; j<zNodes.length; j++) {
				if(zNodes[i].id == zNodes[j].pid) {
					zNodes[i].open = true;
					zNodes[i].nocheck = true;
					break;
				}
			}
		}
		zNodes2 = tree_data.rows[1];
	}
    $.fn.zTree.init($("#treeClassify"), setting, zNodes);
    $.fn.zTree.init($("#treeShop"), setting2, zNodes2);
    
    //设置弹出查询窗口参数
	$("#searchform").dialog({
        height:200,
        width:380,
        resizable:false,
        modal:true,  //这里就是控制弹出为模态
        buttons:{
            "取消":function(){$(this).dialog("close");},
            "重置":function(){
            	$("#searchform input").each(function(){
					$(this).val("");
				});
				$("#key_state").val("");
            },
            "查询":function(){
            	searchParam.shop_id = $("#key_shop_id").val();
            	searchParam.userid = $("#key_userid").val();
            	searchParam.shop_name = $("#key_shop_name").val();
            	searchParam.goods_name = $("#key_goods_name").val();
            	searchParam.state = $("#key_state").val();
            	if(searchParam.shop_id == "") {
				    $("#add_gridTable1").hide();
			    } else {
			    	$("#add_gridTable1").show();
			    }
            	$(this).dialog("close");
            	$("#gridTable1").jqGrid('setCaption', getTitle()).jqGrid('setGridParam').trigger("reloadGrid", [ {page: 1} ]);
            }
        }
    }).dialog("close");
    
    //设置弹出编辑窗口参数
	$("#modifyform").dialog({
        height:450,
        width:720,
        resizable:false,
        modal:true,  //这里就是控制弹出为模态
        buttons:{
            "取消":function(){$(this).dialog("close");},
            "确定":function(){
            	var arrSql = [];
            	var uuid = $("#goods_id").val()=="" ? (new UUID()).toString() : $("#goods_id").val();
            	if($("#goods_id").val() == "") {
            		arrSql.push({
        				sqlID: 'sjc_goods_manage_2',
        				parameters: {
        					shop_id: searchParam.shop_id,
        					userid: searchParam.userid,
        					goods_id: uuid,
        					goods_name: $("#goods_name").val(),
        					detail: ewHTML(),
        					goods_img_id: imgInfo!=null ? imgInfo.id : "",
        					goods_old_price: $("#goods_old_price").val(),
        					goods_price: $("#goods_price").val(),
        					state: $("#state").val()
        				}
        			});
            	} else {
            		arrSql.push({
        				sqlID: 'sjc_goods_manage_3',
        				parameters: {
        					goods_id: $("#goods_id").val(),
        					goods_name: $("#goods_name").val(),
        					detail: ewHTML(),
        					goods_img_id: $("#goods_img_id").val(),
        					goods_old_price: $("#goods_old_price").val(),
        					goods_price: $("#goods_price").val(),
        					state: $("#state").val()
        				}
        			});
        			arrSql.push({
        				sqlID: 'sjc_goods_manage_6',
        				parameters: {
        					goods_id: $("#goods_id").val()
        				}
        			});
            	}
            	
            	if(imgInfo != null) {
        			arrSql.push({
        				sqlID: 'sjc_img_1',
        				parameters: {
        					img_id: imgInfo.id,
        					original_name: imgInfo.name,
        					save_name: imgInfo.saveName,
        					img_type: imgInfo.type,
        					absolute_path: imgInfo.absolutePath,
        					small_absolute_path: imgInfo.smallAbsolutePath,
        					relative_path: imgInfo.relativePath,
        					small_relative_path: imgInfo.smallRelativePath
        				}
        			});
        			
        			arrSql.push({sqlID: 'sjc_goods_manage_9', parameters: {goods_id: uuid, img_id: imgInfo.id, img_type:'0'} });
					arrSql.push({sqlID: 'sjc_goods_manage_13', parameters: {goods_id: uuid} });
					arrSql.push({sqlID: 'sjc_goods_manage_12', parameters: {goods_id: uuid} });
        		}
        		
        		if($("#goods_types").val().length > 0) {
        			var ids = $("#goods_types").val().split(",");
        			for(var i=0; i<ids.length; i++) {
        				arrSql.push({
	        				sqlID: 'sjc_goods_manage_5',
	        				parameters: {
	        					goods_id: uuid,
	        					goods_type_id: ids[i]
	        				}
	        			});
        			}
        		}
        		
        		if(AjaxUtil.command.isSucceed(AjaxUtil.command.executeTransaction(arrSql))) {
    				$("#modifyform").dialog("close");
    				if($("#goods_id").val() == "") {
    					$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid", [ {page: 1} ]);
    				} else {
    					$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid");
    				}
    				$.jqalert("保存成功！");
    			} else {
    				$.jqalert("保存失败！");
    			}
            }
        }
    }).dialog("close");
    
    //设置弹出图片展示窗口参数
	$("#otherform").dialog({
        height:360,
        width:520,
        resizable:false,
        modal:true,
        close: function(event, ui) {
        	$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid");
        }
    }).dialog("close");
    
     //设置图片上传参数
    $('#file_upload').uploadify({
		'swf'      		: basePath + '/web/resources/lib/uploadify/uploadify.swf',
		'uploader'		: basePath + '/server/imageUpload.do',
		'method'		: 'post',							//以post方式上传
		'fileObjName'	: 'file',							//提交时候的字段名，和struts2里面用来接收File的字段名一致
		'fileTypeDesc'	: 'Image Files',					//可上传文件格式的描述
		'fileTypeExts'	: '*.gif; *.jpg; *.jpge; *.png',	//可上传的文件格式 
		'auto'			: true,								//选择一个文件是否自动上传
		'buttonText'	: '上传商品图片',							//上传按钮的文字
        'fileSizeLimit'	: '2MB',							//上传文件的大小限制
        'queueSizeLimit': 1,								//上传数量
        'onUploadSuccess' : function(file, data, response) {	//上传成功后触发的事件
        	imgInfo = $.evalJSON(data);
        	$("#uploadify").hide();
        	$("#imgShow").show();
        	$("#goods_img_id").val(imgInfo.id);
        	$("#uploadImg").attr("src", imgInfo.url);
		}
	});
	
	//设置展示图片上传参数
    $('#file_upload_1').uploadify({
		'swf'      		: basePath + '/web/resources/lib/uploadify/uploadify.swf',
		'uploader'		: basePath + '/server/imageUpload.do',
		'method'		: 'post',							//以post方式上传
		'fileObjName'	: 'file',							//提交时候的字段名，和struts2里面用来接收File的字段名一致
		'fileTypeDesc'	: 'Image Files',					//可上传文件格式的描述
		'fileTypeExts'	: '*.gif; *.jpg; *.jpge; *.png',	//可上传的文件格式 
		'auto'			: true,								//选择一个文件是否自动上传
		'buttonText'	: '上传展示图片',							//上传按钮的文字
        'fileSizeLimit'	: '2MB',							//上传文件的大小限制
        'onUploadSuccess' : function(file, data, response) {	//上传成功后触发的事件
        	var o = $.evalJSON(data);
			var arrSql = [];
			arrSql.push({sqlID: 'sjc_img_1',
				parameters: {
					img_id: o.id,
					original_name: o.name,
					save_name: o.saveName,
					img_type: o.type,
					absolute_path: o.absolutePath,
					small_absolute_path: o.smallAbsolutePath,
					relative_path: o.relativePath,
					small_relative_path: o.smallRelativePath
				}
			});
			arrSql.push({sqlID: 'sjc_goods_manage_9', parameters: {goods_id: upshow_goods_id, img_id: o.id, img_type:'0'} });
			arrSql.push({sqlID: 'sjc_goods_manage_10', parameters: {goods_id: upshow_goods_id, goods_img_id: o.id} });
			arrSql.push({sqlID: 'sjc_goods_manage_12', parameters: {goods_id: upshow_goods_id} });
			if(AjaxUtil.command.isSucceed(AjaxUtil.command.executeTransaction(arrSql))){
				$("#photo_show").append($("<li><img src=\"" + o.url + "\" alt=\"\" /></li>"));
			}
		}
	});
	
	$("#delImg").click(function() {
		imgInfo = null;
		$("#goods_img_id").val("");
		$("#uploadify").show();
    	$("#imgShow").hide();
    	$("#uploadImg").attr("src", "");
    	$('#file_upload-queue').empty();
	});
	
	var temp_shop_id = $("#key_shop_id").val();
    if(temp_shop_id == "") {
	    $("#add_gridTable1").hide();
    } else {
    	var node = null;
    	for(var i=0; i<zNodes2.length; i++) {
    		if(zNodes2[i].id == temp_shop_id) {
    			node = zNodes2[i];
    			break;
    		}
    	}
    	if(node != null) {
	    	$("#key_userid").val(node.userid);
			$("#key_shop_name").val(node.name);
			searchParam.shop_id = temp_shop_id;
			searchParam.shop_name = node.name;
			searchParam.userid = node.userid;
    	} else {
    		$("#add_gridTable1").hide();
    	}
    }
    $("#select_classify").button().click(function() {
		showMenu();
	});
    $("#select_shop").button().click(function() {
		showMenu2();
	});
	
	$("#gridTable1").jqGrid('setCaption', getTitle());
});

var upshow_goods_id = '';
function optImages(id, name) {
	$("#photo_show").empty();
	upshow_goods_id = id;
	
	var data = AjaxUtil.command.executeQuery("sjc_goods_manage_8", {goods_id: id});
	if(AjaxUtil.command.isSucceed(data)) {
		for(var i=0; i<data.rows.length; i++) {
			$("#photo_show").append($("<li><img src=\"" + basePath + data.rows[i].small_relative_path + "\" alt=\"\" /></li>"));
		}
	}
	
	$("#otherform").dialog("open");
	$("#otherform").dialog("option", 'title', name + " > 图片展示");
}

function openSearch() {
	$("#searchform").dialog("open");
}

function openAdd() {
	imgInfo = null;
	$('#file_upload-queue').empty();
    var zTree = $.fn.zTree.getZTreeObj("treeClassify");
	zTree.checkAllNodes(false);
	$("#modifyform input").each(function(){
		$(this).val("");
	});
	$("#state").val("1");
	$("#uploadify").show();
    $("#imgShow").hide();
    $("#uploadImg").attr("src", "");
	
	$("#modifyform").dialog("open");
	$("#modifyform").dialog("option", 'title', '添加');
	ewHTML("");
}

function openEdit() {
	var selectedIds = $("#gridTable1").jqGrid("getGridParam", "selarrrow");
	if(selectedIds.length != 1) {
		$.jqalert("请选择一条要编辑的记录");
		return;
	}
	var data = getRow(selectedIds[0]);
	if(data == null) {
		$.jqalert("请选择一条要编辑的记录");
		return;
	}
	
	imgInfo = null;
	$('#file_upload-queue').empty();
	var zTree = $.fn.zTree.getZTreeObj("treeClassify");
	zTree.checkAllNodes(false);
	$("#modifyform input").each(function(){
		$(this).val("");
	});
	$("#shop_id").val(data.shop_id);
	$("#goods_id").val(data.goods_id);
	$("#goods_name").val(data.goods_name);
	if(data.goods_img_id != "") {
		$("#uploadify").hide();
    	$("#imgShow").show();
	} else {
		$("#uploadify").show();
    	$("#imgShow").hide();
	}
	$("#goods_img_id").val(data.goods_img_id);
	$("#uploadImg").attr("src", basePath + data.small_relative_path);
	$("#goods_old_price").val(data.goods_old_price);
	$("#goods_price").val(data.goods_price);
	$("#state").val(data.state);
	$("#goods_types").val(data.goods_types);
	$("#classify").val(data.type_names);
	
	$("#modifyform").dialog("open");
	$("#modifyform").dialog("option", 'title', '编辑');
	ewHTML(data.detail);
}

function openDel() {
	var selectedIds = $("#gridTable1").jqGrid("getGridParam", "selarrrow");
	$.jqconfirm("确定删除选中的记录吗?", "确认提示",function() {
		var arrSql = [];
		for(var i=0; i<selectedIds.length; i++) {
			arrSql.push({sqlID: 'sjc_goods_manage_4', parameters: {goods_id: selectedIds[i]} });
       		arrSql.push({sqlID: 'sjc_goods_manage_6', parameters: {goods_id: selectedIds[i]} });
       		arrSql.push({sqlID: 'sjc_index_goods_3', parameters: {id: selectedIds[i]} });
       		arrSql.push({sqlID: 'sjc_shop_goods_classify_8', parameters: {goods_id: selectedIds[i]} });
		}
		if(AjaxUtil.command.isSucceed(AjaxUtil.command.executeTransaction(arrSql))){
			$("#gridTable1").jqGrid('setGridParam').trigger("reloadGrid");
			$.jqalert("删除成功！");
		} else {
			$.jqalert("删除失败！");
		}
	});
}

function getRow(id) {
	if(rows == null) return null;
	for(var i=0; i<rows.length; i++) {
		if(rows[i].goods_id == id) return rows[i];
	}
	return null;
}

function ewHTML(val) {
	var o_Editor = document.getElementById("eWebEditor1").contentWindow;
	if(val === undefined) {
		return o_Editor.getHTML();
	} else {
		o_Editor.setHTML(val);
	}
}

function getTitle() {
	var s = "商品管理 【";
	if(searchParam.shop_name != "") s += searchParam.shop_name + "&nbsp;&nbsp;";
	else s += "所有店铺&nbsp;&nbsp;";
	if(searchParam.goods_name != "") s += searchParam.goods_name + "&nbsp;&nbsp;";
	s += $("#key_state").find("option:selected").text();
	s += "】";
	return s;
}

var setting = {
	check: {
		enable: true,
		chkboxType: {"Y":"", "N":""}
	},
	view: {
		dblClickExpand: false
	},
	data: {
		simpleData: {
			enable: true,
			pIdKey: "pid"
		}
	},
	callback: {
		beforeClick: beforeClick,
		onCheck: onCheck
	}
};

var zNodes = [];

function beforeClick(treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeClassify");
	zTree.checkNode(treeNode, !treeNode.checked, null, true);
	return false;
}

var select_nodes;
function onCheck(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeClassify"),
	nodes = zTree.getCheckedNodes(true),
	v = "",
	ids = "";
	if(nodes.length > 3) {
		zTree.checkAllNodes(false);
		for(var i=0; i<select_nodes.length; i++) {
			zTree.checkNode(select_nodes[i], true, false);
		}
		nodes = select_nodes;
		return ;
	}
	select_nodes = nodes;
	for (var i=0, l=nodes.length; i<l; i++) {
		v += nodes[i].name + ",";
		ids += nodes[i].id + ",";
	}
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	if (ids.length > 0 ) ids = ids.substring(0, ids.length-1);
	$("#goods_types").val(ids);
	var classifyObj = $("#classify");
	classifyObj.attr("value", v);
}

function showMenu() {
	var classifyObj = $("#classify");
	var classifyOffset = $("#classify").offset();
	$("#menuContent").css({left:classifyOffset.left + "px", top:classifyOffset.top + classifyObj.outerHeight() + "px"}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("#menuContent2").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "classify" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0
		 || event.target.id == "key_shop_name" || event.target.id == "menuContent2" || $(event.target).parents("#menuContent2").length>0)) {
		hideMenu();
	}
}

var setting2 = {
	view: {
		dblClickExpand: false,
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable: true,
			pIdKey: "pid"
		}
	},
	callback: {
		beforeClick: beforeClick2,
		onClick: onClick2
	}
};

var zNodes2 =[];

function beforeClick2(treeId, treeNode) {
	var check = (treeNode && !treeNode.isParent);
	if (!check) alert("只能选择店铺...");
	return check;
}

function onClick2(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeShop"),
	nodes = zTree.getSelectedNodes(),
	v = "";
	if(nodes.length == 1) {
		v = nodes[0].name;
		$("#key_userid").val(nodes[0].userid);
		$("#key_shop_id").val(nodes[0].id);
	} else {
		$("#key_userid").val("");
		$("#key_shop_id").val("");
	}
	var shopObj = $("#key_shop_name");
	shopObj.attr("value", v);
}

function showMenu2() {
	var shopObj = $("#key_shop_name");
	var shopOffset = $("#key_shop_name").offset();
	$("#menuContent2").css({left:shopOffset.left + "px", top:shopOffset.top + shopObj.outerHeight() + "px"}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}